﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using DotNetARX;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace CAD.Demo
{
    public static class HelloHelper
    {
        public static ObjectId AddToModelSpace(this Database db, Entity ent)
        {
            ObjectId entId = ObjectId.Null;//用于返回添加到模型空间中的实体ObjectId
            //定义一个指向当前数据库的事务处理，以添加直线
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {

                //以读方式打开块表
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                var spaceId = bt[BlockTableRecord.ModelSpace];

                //以写方式打开模型空间块表记录.
                if (trans.GetObject(spaceId, OpenMode.ForWrite) is BlockTableRecord btr)
                {
                    entId = btr.AppendEntity(ent);//将图形对象的信息添加到块表记录中
                    trans.AddNewlyCreatedDBObject(ent, true);//把对象添加到事务处理中
                }
                trans.Commit();//提交事务处理
            }
            return entId; //返回实体的ObjectId
        }


        public static ObjectId AddToModelSpace(this Database database, Entity ent, bool needLock = true)
        {
            ObjectId entId = ObjectId.Null;//用于返回添加到模型空间中的实体ObjectId
             
            Action action = new Action(() =>
            {
                using (Transaction trans = database.TransactionManager.StartTransaction())
                {
                    //以读方式打开块表
                    BlockTable bt = (BlockTable)trans.GetObject(database.BlockTableId, OpenMode.ForRead);
                    var spaceId = bt[BlockTableRecord.ModelSpace];

                    //以写方式打开模型空间块表记录.
                    if (trans.GetObject(spaceId, OpenMode.ForWrite) is BlockTableRecord btr)
                    {
                        entId = btr.AppendEntity(ent);//将图形对象的信息添加到块表记录中
                        trans.AddNewlyCreatedDBObject(ent, true);//把对象添加到事务处理中
                    }
                    trans.Commit();//提交事务处理
                }
            });
            if (needLock)
            {

                Document document = database.GetDocument();
                using (DocumentLock docLock = document.LockDocument())
                {
                    //add to modelspace 加入模型空间
                    action.Invoke();
                }
            }
            else
            {
                action.Invoke();
            }
             
            return entId; //返回实体的ObjectId
        }


    }
}
